package com.tuanzi.loan.business.service.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.util.MessageInfo;
import com.base.common.util.SendsslEmailUtil;
import com.google.common.collect.Lists;
import com.tuanzi.loan.business.service.system.AnnouncementService;
import com.tuanzi.loan.business.service.system.SystemUserService;
import com.tuanzi.loan.core.aspect.Debug;

import lombok.extern.log4j.Log4j;

/**
 * @author Ray 2017/09/21
 */

@Debug
@Log4j
@Service
@Transactional
public class AnnouncementScheduler {

	@Autowired
	private AnnouncementService announcementService;
	@Autowired
	private SystemUserService systemUserService;

	@Scheduled(cron = "${cron.send-announcement-email}")
	public void sendAnnouncementEmail() {
		announcementService.findAllNeedToSendAnnouncements().stream().forEach(x -> {

			String content = "公告标题: " + x.getTitle() + " <br/> " + "公告内容: " + x.getContent();
			systemUserService.findAllHasEmailSystemUser().parallelStream().forEach(y -> this.sendAnnouncementEmail(y.getEmail(), content));
			x.setHasSendEmail(true);
			announcementService.saveOrUpdate(x);
		});
	}

	private void sendAnnouncementEmail(String email, String content) {
		try {
			String user = "jbsystem@xmiles.cn";
			String passwd = "KZYByFk5Rfh52J2a";
			MessageInfo msg = new MessageInfo();
			msg.setTo(Lists.newArrayList(email));
			msg.setSubject("菠萝天眼公告");
			msg.setMsg(content);
			msg.setMsgType("text/html;charset=utf-8");
			SendsslEmailUtil.sslSend(msg, user, passwd);
		} catch (Exception e) {
			log.error("短信后台邮件报告发送失败", e);
		}
	}
}
